//

import {Button, Card, Col, Divider, Input, Row, Select, Switch, Table, Tag} from 'antd';
import React, {PureComponent} from "react";
import {connect} from "umi";
import {Drawer} from "antd/es";
import Form from "antd/es/form";
import TextArea from "antd/es/input/TextArea";
import {
  randomRgbColor,
  getAbilityById,

  listByAbility,
  guid, listScore, formatScore
} from "@/pages/RadarChart/base/DataLoad";
import PlusOutlined from "@ant-design/icons/lib/icons/PlusOutlined";
import SelectSearch from "@/pages/RadarChart/base/SelectSearch";
import NumInput from "@/pages/RadarChart/base/NumInput";
import RadarChartView from "@/pages/RadarChart/components/RedarChartView";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";


class AbilityEdit extends PureComponent {

  state = {
    drawerVisible: false,
    drawerData: {}
  }

  formRef = React.createRef();

  columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: "name",
    },
    {
      title: '能力权重',
      dataIndex: 'rule',
      render: (data) => {
        if (data == null) {
          return "";
        }

        let str = "";
        let sumWeight = 0;
        for (let i in data) {

          let name = getAbilityById(i).name;
          let weight = data[i];
          str += "+" + name + "*" + weight;
          sumWeight += weight;
        }
        if (str != "") {
          str = str.substr(1, str.length);
          str = "(" + str + ")/" + sumWeight;
        }


        return str;
      },
      key: 'weight'
    }, {
      title: '操作',
      key: '操作',
      render: (text, record) => {


        return <div>
          <Button onClick={() => this.edit(record)}>编辑</Button>
          <Button onClick={() => this.delete(record.jobId)}>删除</Button>
        </div>
      }

    }
  ];

  edit(data) {

    this.openDrawer(data);
  }

  delete(id) {
    const dispatch = this.props.dispatch;
    return dispatch({
      type: 'radarCharModel/deleteJob',
      payload: {id: id},
    }).then(() => {
      this.list();
    });
  }

  list = () => {
    const dispatch = this.props.dispatch;


    return dispatch({
      type: 'radarCharModel/listJob',
      payload: {},
    });
  }

  componentDidMount() {
    this.list();
  }

  renderForm(data) {
    if (this.formRef.current) {
      this.state.drawerData = data;
      this.formRef.current.resetFields();
      this.formRef.current.setFieldsValue(data);
    } else {
      setTimeout(() => {
        this.renderForm(data)
      }, 100);
    }
  }

  openDrawer(data) {

    this.state.drawerData = JSON.parse(JSON.stringify(data));
    this.renderForm(data);

    this.setState({drawerVisible: true});
  }

  onClose() {
    this.setState({drawerVisible: false})
  }

  onFinish(data) {

    data = {...data, ...this.parseRuleArray(this.state.drawerData)};
    console.log(data);
    const dispatch = this.props.dispatch;
    dispatch({
      type: 'radarCharModel/saveJob',
      payload: data,
    }).then(() => {
      this.list();
    });
  }

  parseRuleArray(drawerData) {

    let ruleArray = drawerData.array;
    if (ruleArray == null) {
      ruleArray = [];
    }
    let obj = {...getAbilityById(this.state.drawerData.abilityId)};
    obj.base = {};
    obj.important = [];
    obj.rule = {};
    obj.color = drawerData.color;
    obj.name = drawerData.name;
    obj.jobId = drawerData.jobId;
    for (let item of ruleArray) {
      if (item.important) {
        obj.important.push(item.abilityId);
      }
      if (item.baseNum != 60) {
        obj.base[item.abilityId] = new Number(item.baseNum);
      }
      obj.rule[item.abilityId] = item.weight == null ? 0 : item.weight;

    }
    return obj;
  }

  timeoutRecord = null;

  flushChart() {
    clearTimeout(this.timeoutRecord);
    let drawerData = this.state.drawerData;

    this.timeoutRecord = setTimeout(() => {
      let obj = this.parseRuleArray(drawerData);

      this.setState({drawerData: obj});
    }, 100);
  }

  render() {
    let drawerData = this.state.drawerData;
    let job = [];
    let exclude = [];
    job.push(drawerData);
    if (drawerData.color == null) {
      drawerData.color = randomRgbColor();
    }
    if (drawerData.base == null) {
      drawerData.base = {};
    }
    //初始化form list data
    drawerData.array = [];
    let array = drawerData.array;
    let map = drawerData.rule;
    for (let i in map) {
      let object = {...getAbilityById(i)};
      object.weight = map[i];
      if (drawerData.important && drawerData.important.indexOf(i) != -1) {
        object.important = true;
      } else {
        object.important = false;
      }
      if (drawerData.base && drawerData.base[i]) {
        object.baseNum = new Number(drawerData.base[i]);
      } else {
        object.baseNum = new Number(60);
      }
      exclude.push(i);
      array.push(object);
    }

    return <div>

      <Drawer
        title={this.state.drawerData.jobId ? "编辑工作" : "新增工作"}
        placement="right"
        closable={false}
        width={"80%"}
        onClose={() => {
          this.onClose()
        }}
        visible={this.state.drawerVisible}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={() => {
              this.onClose()
            }} style={{marginRight: 8}}>
              Cancel
            </Button>
            <Button onClick={() => {
              this.onClose();
              this.formRef.current.submit();
            }} type="primary">
              Submit
            </Button>
          </div>
        }
      >
        <Row gutter={16}>
          <Col span={11} style={{borderRight: "1px solid gray"}}>
            <RadarChartView job={job} colors={[drawerData.color]}></RadarChartView>
          </Col>
          <Col span={13}>
            <Form ref={this.formRef} name="control-hooks" onFinish={(data) => {


              this.onFinish(data);
            }}>
              <Form.Item name="jobId">
                <Input type={"hidden"}/>
              </Form.Item>
              <Form.Item name="name" rules={[{required: true}]} label={"职位名称"}>
                <Input style={{marginLeft: "1em"}} type={"text"} onChange={(e) => {
                  this.state.drawerData.name = e.currentTarget.value;
                  this.flushChart();
                }}/>
              </Form.Item>

              <div>
                {array.map((item, index) => {


                  return <Row gutter={16} key={index}>
                    <Col span={12}>
                      <Form.Item
                        label={"指标"}
                        required={true}

                      >
                        {/*fixme select 做成从后台查数据*/}
                        <SelectSearch
                          key={guid()}
                          // style={{marginLeft:"1em"}}
                          exclude={exclude}
                          mark={item} onChange={(value, mark, type) => {

                          item.abilityId = value;
                          item = {item, ...getAbilityById(value)};

                          this.flushChart();

                        }} load={(value, call) => {
                          let array = listByAbility(value);

                          call(array);
                        }}
                          data={item.name ? [{name: item.name, value: item.id}] : []}
                          defaultValue={item.id}

                        ></SelectSearch>

                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label={"权重"}
                        required={true}

                      >
                        <NumInput min={0} max={100} onChange={(value, mark, type) => {
                          item.weight = value;
                          if (type != "init") {

                            this.flushChart();
                          }
                        }} defaultValue={item.weight ? item.weight : 1}></NumInput>
                      </Form.Item>
                    </Col>
                    <Col span={10}>
                      <Form.Item
                        label={"是否是关键能力"}
                        required={true}

                      >
                        <Switch checkedChildren="关键" unCheckedChildren="非关键"
                                defaultChecked={item.important}
                                onChange={(value) => {
                                  item.important = value;
                                  this.flushChart();
                                }}></Switch>
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        label={"合格分数"}
                        required={true}
                      >
                        <SelectSearch
                          key={guid()}

                          mark={item} onChange={(value, mark, type) => {

                          item.baseNum = new Number(value).toFixed(0);

                          if (type != "init") {
                            this.flushChart();
                          }

                        }} load={(value, call) => {
                          let array = listScore();

                          call(array);
                        }}
                          data={listScore()}
                          defaultValue={formatScore(item.baseNum)}

                        ></SelectSearch>
                        {/*<NumInput min={0} max={100} onChange={(value, mark, type) => {*/}
                        {/*  item.baseNum = value;*/}
                        {/*  if (type != "init") {*/}
                        {/*    this.flushChart();*/}

                        {/*  }*/}
                        {/*}}*/}
                        {/*          defaultValue={item.baseNum}></NumInput>*/}
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <MinusCircleOutlined
                        className="dynamic-delete-button"
                        style={{margin: '0 8px'}}
                        onClick={() => {
                          drawerData.array.splice(index, 1);

                          this.flushChart();
                        }}
                      />
                    </Col>

                  </Row>

                })}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => {

                      drawerData.array.push({});
                      this.flushChart();
                    }}
                    style={{width: '60%'}}
                  >
                    <PlusOutlined/> 添加能力
                  </Button>
                </Form.Item>
              </div>


            </Form>
          </Col>
        </Row>
      </Drawer>

      <Button onClick={() => this.openDrawer({})}>新增职位</Button>
      <Table dataSource={this.props.radarCharModel.job} columns={this.columns}></Table>

    </div>;
  }
}

export default connect(({radarCharModel, loading}) => ({
  radarCharModel: radarCharModel,
}))(AbilityEdit);
